﻿/***************************************************
//  Copyright (c) Premium Tax Free 2011
***************************************************/

using System;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Security.Permissions;
using System.Security.Principal;
using System.Threading;
using System.Web;
using System.Web.Services;
using PremierTaxFree.PTFLib;
using PremierTaxFree.PTFLib.Data;
using PremierTaxFree.PTFLib.Extensions;
using PremierTaxFree.PTFLib.Security;
using PremierTaxFree.PTFLib.Web;

namespace ReceivingService
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class ReceivingWebService : WebService
    {
        public ReceivingWebService()
        {
            IIdentity idenity = new GenericIdentity("Administrator");
            IPrincipal principal = new GenericPrincipal(idenity, new string[] { "Administrators" });
            Thread.CurrentPrincipal = principal;
        }

        public static readonly Hashtable Table = Hashtable.Synchronized(new Hashtable());

        [WebMethod]
        [PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
        public string Test()
        {
            return DateTime.Now.ToString();
        }

        [WebMethod]
        [CompressionExtension]
        [PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
        //[SoapHeader("AuthHeader", Required = true)]
        public void SaveDataXmlText(string xmlContent)
        {
            ProtectedXml doc = new ProtectedXml(ProtectionOptions.SignAndEncript);
            doc.LoadXml(xmlContent);
            InsertData(doc);
        }

        [WebMethod]
        [CompressionExtension]
        [PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
        public void SaveDataXmlData(byte[] fileData)
        {
            ProtectedXml doc = fileData.CreateXmlData(ProtectionOptions.SignAndEncript);
            InsertData(doc);
        }

        [WebMethod]
        [CompressionExtension]
        [PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
        public void SaveMessageXmlText(string xmlContent)
        {
            ProtectedXml doc = new ProtectedXml(ProtectionOptions.SignAndEncript);
            doc.LoadXml(xmlContent);
            InsertMessages(doc);
        }

        [WebMethod]
        [CompressionExtension]
        [PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
        public void SaveMessageXmlData(byte[] messageData)
        {
            ProtectedXml doc = messageData.CreateXmlData(ProtectionOptions.SignAndEncript);
            InsertMessages(doc);
        }

        #region VALUES

        //CurrentVersion - Version of VScan application
        [WebMethod]
        [PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
        public object GetValue(string key)
        {
            return Table[key];
        }

        [WebMethod]
        [PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
        public void SetValue(string key, object value)
        {
            Table[key] = value;
        }

        #endregion

#warning DO NOT USE [CompressionExtension] WHEN YOU RETURN DATA! DOESN'T WORK.

        [WebMethod]
        [PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
        public string[] GetFiles()
        {
            string path = Table[Strings.Transferring_LocalDeploymentPath].ToStringSf();
            return Array.ConvertAll(Directory.GetFiles(path), (f) => { return Path.GetFileName(f); });
        }

        [WebMethod]
        [PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
        public byte[] GetFile(string file)
        {
            string path = Table[Strings.Transferring_LocalDeploymentPath].ToStringSf();
            string filePath = Path.Combine(path, file);
            byte[] buffer = File.ReadAllBytes(filePath);
            return buffer;
        }

        private static void InsertData(ProtectedXml data)
        {
            string clientIP = HttpContext.Current.Request.UserHostAddress;

            DataSchemaServer.XML_DATADataTable table = new DataSchemaServer.XML_DATADataTable();
            data.WriteTo(table);

            foreach (DataSchemaServer.XML_DATARow row in table.Rows)
            {
                DataAccess.InsertFileAsync_Server(
                    row.FileName,
                    clientIP,
                    row.CountryCode,
                    row.RetailerID,
                    row.VoucherID,
                    row.VoucherImage,
                    row.BarCodeImage);
            }
        }

        private static void InsertMessages(ProtectedXml data)
        {
            //TODO: Save IP address as well
            string clientIP = HttpContext.Current.Request.UserHostAddress;

            DataSchemaServer.XML_MSGDataTable table = new DataSchemaServer.XML_MSGDataTable();
            data.WriteTo(table);

            foreach (DataSchemaServer.XML_MSGRow row in table.Rows)
            {
                DataAccess.InsertMessageAsync(row.Message, row.Source, (eMessageTypes)row.Type, row.StackTrace, true);
            }
        }
    }
}

//***********************************
//Know-how
//string ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
//***********************************